<?php
/**
 * vim: tabstop=4
 * 
 * @license		http://www.gnu.org/licenses/gpl.html GPL Version 3
 * @author		Ian Moore <imooreyahoo@gmail.com>
 * @copyright	Copyright (c) 2011 Ian Moore
 * @version		$Id: minidlna.inc 65 2011-12-09 20:00:59Z imooreyahoo@gmail.com $
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this file. If not, see <http://www.gnu.org/licenses/>.
 */
require_once("openmediavault/object.inc");
require_once("openmediavault/error.inc");
require_once("openmediavault/util.inc");
require_once("openmediavault/rpc.inc");

class MiniDLNARpc extends OMVRpc {

	const xpathRoot = '//services/minidlna';

	public function __construct() {
		$this->methodSchemata = array(
            "set" => array('{
                "type":"object",
                "properties":{
                    "enable":{"type":"boolean"},
                    "rescan":{"type":"boolean","optional":true},
                    "name":{"type":"string","optional":true},
					"port":{"type":"integer"},
					"strict":{"type":"boolean"},
					"tivo":{"type":"boolean"},
					"folders":{
						"type":"array",
                        "items":{
                            "type":"object",
                            "properties":{
                                "sfref":{'.$GLOBALS['OMV_JSONSCHEMA_UUID'].'},
								"mtype":{"type":"string"}
							}
						}
					}

                }
            }')
		);

	}

    /**
     * Safe config getting amd setting
     */
    public function __call($name, $args) {

        // Configuration methods
        if(substr($name,0,6) == 'config') {

            // Correct method name
            $name = substr($name,6);
            $name[0] = strtolower($name[0]);

            global $xmlConfig;
            $object = call_user_func_array(array($xmlConfig,$name),$args);
            switch($name) {
                case 'delete':
                    if($object === false)
                        throw new OMVException(OMVErrorMsg::E_CONFIG_OBJECT_NOT_FOUND, $args[0]);
                    break;
                case 'save':
                    if($object === false)
                        throw new OMVException(OMVErrorMsg::E_CONFIG_SAVE_FAILED, $xmlConfig->getError());
                    break;
                case 'set':
                case 'replace':
                    if($object === false)
                        throw new OMVException(OMVErrorMsg::E_CONFIG_SET_OBJECT_FAILED);
                    break;
                default:
                    if(is_null($object))
                        throw new OMVException(OMVErrorMsg::E_CONFIG_GET_OBJECT_FAILED, $args[0]);
            }

            return $object;


        }
        throw new Exception("Method ".__CLASS__."::".$name." does not exist.");
    }

    /**
     * Verify that the current user is an admin, and validate method args
     */
    private function _validate($mname='',$args=array()) {

        // Check permissions
        $this->validateSession();
        if (!$this->hasRole(OMV_ROLE_ADMINISTRATOR)) {
            throw new OMVException(OMVErrorMsg::E_RPC_SERVICE_INVALID_PERMISSION);
        }
        $this->commitSession();

        // Check incoming data
        if($mname)
            $this->validateParams($mname, $args);
    }


	/**
	 * Get settings directly from os
	 */
	function get() {

		$this->_validate();

		$conf = $this->configGet(self::xpathRoot);

		$conf['folders'] = array();

		$folders = $this->configGetList(self::xpathRoot."/folders/folder");

		// enrich names
		foreach($folders as $f) {
			try {
				$sf = $this->configGet("//system/shares/sharedfolder[uuid='{$f['sfref']}']");
			} catch (Exception $e) {
				continue;
			}

			$f['name'] = $sf['name'];
			$conf['folders'][] = $f;
		}

		return $conf;

	}

	/**
	* Set settings
	*/
	function set($object) {

       // Check incoming data
        $this->_validate(__METHOD__,func_get_args());

		$oldconf = $this->get();

        foreach(array('enable','strict','tivo') as $k)
            $object[$k] = array_boolval($object,$k);

		// Rescan media folders
		$rescan = array_boolval($object,'rescan');
		unset($object['rescan']);

		$folders = $object['folders'];
		$object['folders'] = array();

        // Set configuration object
        $this->configReplace(self::xpathRoot, $object);

		foreach($folders as $f) {
			$this->configSet(self::xpathRoot.'/folders',
				array('folder'=>$f));
		}

		$object['folders'] = $folders;

        $this->configSave();

        // Notify general configuration changes
        $dispatcher = &OMVNotifyDispatcher::getInstance();
        $dispatcher->notify(OMV_NOTIFY_MODIFY,
            "org.openmediavault.services.minidlna", $object, $oldconf, $rescan);



	}
}

